import IconUpload from '@/components/antd-comp/icon-upload/index'
import { showMessage } from '@/components/antd-comp/message'
import CustomSelect from '@/components/antd-comp/select/CustomSelect'
import ThemeBtn from '@/components/antd-comp/theme-btn/index'
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/bs-ui/dialog'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/bs-ui/table'
import {
  createTool,
  deleteTool,
  deleteToolCount,
  downloadToolSchema,
  getToolVersion,
  saveTool,
  testToolApi,
  updateTool
} from '@/controllers/API/tools'
import { captureAndAlertRequestErrorHoc } from '@/controllers/request'
import { BackIcon } from '@/icons/Back/index'
import { useDictStore } from '@/store/dictStore'
import { usePluginStore } from '@/store/pluginStore'
import { ExclamationCircleFilled } from '@ant-design/icons'
// import { DownOutlined, ExclamationCircleFilled } from '@ant-design/icons'
// import { Input as AntInput, Button as AntdButton, Button, Dropdown, Form, Input, Modal, Radio, Space } from 'antd'
import type { MenuProps } from 'antd'
import { Input as AntInput, Button as AntdButton, Button, Form, Modal, Radio } from 'antd'
import { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useNavigate, useParams } from 'react-router-dom'
import Edition from './components/Edition'

import { showError } from '@/components/antd-comp/message/useNotification'
import { Func } from '@/permissions/constants'
import { useFuncsStore } from '@/store/funcStore'
import { useBuriedEvent } from '@/util/buried'
import { cloneDeep, debounce, trimStart } from 'lodash'
import AceEditor from 'react-ace'
import { toolUsedCountByFlowApi } from '../workflow/API'
import './css/editToolPage.less'
import './css/interface.less'

const { confirm } = Modal

const { TextArea } = AntInput

const initFormData = {
  toolName: '',
  schemaContent: `{  # 开始整个JSON对象
  "openapi": "3.1.0",  # 指定使用的OpenAPI规范版本
  "info": {  # 描述API的基本信息
    "title": "Untitled",  # API的标题
    "description": "Your OpenAPI specification",  # 对API功能的简短描述
    "version": "v1.0.0"  # API的版本号
  },
  "servers": [  # 定义服务器URL
    {
      "url": ""  # API服务的URL，这里为空字符串，应该填写实际的服务器地址
    }
  ],
  "paths": {},  # 定义路径（Endpoints），目前没有定义任何路径
  "components": {  # 定义组件，如数据模型、安全方案等
    "schemas": {}  # 数据模型定义，目前没有定义任何数据模型
  }
}  # 结束整个JSON对象
`,
  authType: 'basic',
  apiKey: '',
  authMethod: 'none',
  customHeader: '',

  category_code: '',
  description: '',
  fileList: [],
  version: '',
  logo: ''
}

const EditTool = forwardRef((props: any, ref) => {
  /**
   * 功能权限限制
   */
  const { hasFuncPermission } = useFuncsStore()
  const { pluginBuriedEvent } = useBuriedEvent()

  const navigate = useNavigate()
  // @ts-expect-error : Argument of type 'pluginDetail' is effective
  const { pluginDetail: tool } = usePluginStore()
  const [editShow, setShow] = useState(true)

  const { id } = useParams()

  const setEditShow = bln => {
    if (!bln) {
      // 关闭弹窗初始化数据
      formState.setFieldsValue({ ...initFormData })
      setTableData([])
    }
    setShow(bln)
  }
  const [delShow, setDelShow] = useState(false)

  const schemaUrl = useRef('')
  // const [formState, formState.setFieldsValue] = useState({ ...formData })

  const [formState] = Form.useForm<any>()

  const authMethodValue = Form.useWatch('authMethod', formState)

  const fromDataRef = useRef<any>({}) // 与formState同步，fromDataRef属性更多，透传保存

  // 表格数据（api接口列表）
  const [tableData, setTableData] = useApiTableData()

  // 备份初始已配置OpenAPI工具,用于保持相同工具的更新时间和测试状态
  const toolsChildrenMapBak = useRef({})
  const serverHostBak = useRef('')

  // 增加默认标签
  const defaultIcon = useRef('')
  const setDefaultIcon = val => {
    defaultIcon.current = val
  }

  // ace  编码模式
  const [aceMode, setAceMode] = useState<'json' | 'yaml' | 'plain_text'>('json')
  const handelAceModeChange = data => {
    if (!data || trimStart(data).startsWith('{')) {
      setAceMode('json')
    } else {
      setAceMode('yaml')
    }
  }

  const [typeList, setTypeList] = useState([])
  const { loadDictOptions } = useDictStore()
  const initData = (type = 'category') => {
    loadDictOptions(type).then(res => {
      //setTypeList(res)
    })
  }

  const handleChangeTab = (...item) => {
    console.log(item, 'item')
  }

  const [versionList, setVersionList] = useState([])
  const getVersions = id => {
    getToolVersion(id).then(res => {
      res.list = res.list.map(item => {
        // item.label = item.name + `（${item.version}）`
        item.label = item.version
        item.childrenItem = item.children
        delete item.children

        return {
          ...item
        }
      })

      setVersionList(res.list)
    })
  }

  const cur_tool_id = useRef(undefined)
  useEffect(() => {
    // Id != 0 就是编辑
    if (id !== '0') {
      fromDataRef.current = tool

      /* 查看 */
      if (tool.hidType === 'listSee') {
        SetSeeType(false)
      }
      const editValue = {
        toolName: tool.name,
        schemaContent: tool.openapi_schema,
        authType: tool.auth_type,
        apiKey: tool.api_key,
        authMethod: tool.auth_method === 1 ? 'apikey' : 'none',
        customHeader: '',

        category_code: tool.category_code,
        description: tool.description,
        logo: tool.logo,
        fileList: [],
        version: tool.version
      }
      // 记录初始配置信息
      lastSchemaContent.current = tool.openapi_schema
      // handelAceModeChange(tool?.openapi_schema)
      setAceMode('plain_text')

      const editFormData = {
        ...initFormData,
        ...editValue
      } as any

      setEditShow(true)
      setDelShow(true) // 删除按钮

      serverHostBak.current = tool.server_host
      const apiTools = cloneDeep(tool.children) || []
      const apiToolsMap = {}
      apiTools.forEach(item => {
        apiToolsMap[item.extra] = item
      })
      toolsChildrenMapBak.current = apiToolsMap
      setTableData(tool.children)
      initData()

      cur_tool_id.current = tool.tool_id
      if (hasFuncPermission([Func.tools.version], false)) {
        // 获取历史版本
        getVersions(tool.tool_id)
      }

      // 暂存info
      SetoldseeInfoNum(editFormData.version)

      formState.setFieldsValue(editFormData)
    } else {
      setEditShow(true)
      setDelShow(false)
      initData()

      formState.setFieldsValue(initFormData)
    }

    console.log(formState.getFieldsValue(), 'formState')
  }, [])

  const handleInputChange = e => {
    const { name, value } = e.target
    formState.setFieldsValue({
      [name]: value
    })
  }

  // 发送请求给后端获取Schema
  const handleImportSchema = () => {
    // http://192.168.106.120:3002/openapi-test.json
    captureAndAlertRequestErrorHoc(downloadToolSchema({ download_url: schemaUrl.current })).then(res => {
      schemaUrl.current = ''
      if (!res) return
      fromDataRef.current = { ...res, id: fromDataRef.current.id }
      const fetchedSchema = res.openapi_schema // 替换为后端返回的Schema
      formState.setFieldsValue({
        schemaContent: fetchedSchema
      })

      setTableData(res.children)
    })
  }

  const lastSchemaContent = useRef('')

  // 根据模板设置Schema内容
  const handleSelectTemplate = (key = '') => {
    if (!editShow) return

    const file_content = key ? Example[key] : formState.getFieldValue('schemaContent')
    // 内容无变化时不做任何处理
    if (lastSchemaContent.current === file_content) {
      if (key) {
        handelAceModeChange(file_content)
      }
      return
    }
    file_content &&
      downloadToolSchema({ file_content }).then(res => {
        schemaUrl.current = ''
        if (!res) return
        fillSchemaInfo(res.children, res.server_host)
        fromDataRef.current = { ...res, id: fromDataRef.current.id }
        const fetchedSchema = res.openapi_schema // 替换为后端返回的Schema
        formState.setFieldsValue({
          schemaContent: fetchedSchema
        })
        lastSchemaContent.current = fetchedSchema
        if (key) {
          handelAceModeChange(fetchedSchema)
        }
        setTableData(res.children)
      })
  }

  // server_host未发生变化时对已存在的工具填充测试状态和更新时间
  const fillSchemaInfo = (toolsChildren: [], serverHost) => {
    console.log('fillSchemaInfo', serverHostBak.current, serverHost)
    if (toolsChildren.length > 0 && serverHostBak.current === serverHost) {
      toolsChildren.forEach((item: any) => {
        const oldItem = toolsChildrenMapBak.current[item.extra]
        if (oldItem) {
          item.update_time = oldItem.update_time
          item.pass_test = oldItem.pass_test
        }
      })
    }
  }

  // 先删除编辑时的颜色控制，发生变更和编辑时直接全部显示灰色
  const handleAceDataChange = value => {
    // let mode: 'yaml' | 'json' = 'yaml'
    // if (value && trimStart(value).startsWith('{')) {
    //   mode = 'json'
    // }
    // if (aceMode !== mode) {
    //   setAceMode(mode)
    // }
    setAceMode('plain_text')
  }

  const handelVersionChange: MenuProps['onClick'] = (data: any) => {
    /* 存version 点击回退用筛选 */
    SetoldseeNum(1)
    SetoldseeInfoNum(formState.getFieldsValue().version)

    const tool = data || {}

    const editValue = {
      toolName: tool.name,
      schemaContent: tool.openapi_schema,
      authType: tool.auth_type,
      apiKey: tool.api_key,
      authMethod: tool.auth_method === 1 ? 'apikey' : 'none',
      customHeader: '',

      category_code: tool.category_code,
      description: tool.description,
      logo: tool.logo,
      fileList: [],
      version: tool.version
    }

    setEditShow(true)
    setDelShow(true) // 删除按钮
    setTableData(tool.childrenItem)
    initData()

    // 获取历史版本
    getVersions(tool.tool_id)

    formState.setFieldsValue(editValue)

    SetRecordsHid(false)
    setAceMode('plain_text')
    fromDataRef.current.version = tool.version
  }

  const refreshPage = () => {
    localStorage.setItem('plugin_tool_id', fromDataRef.current.version || '1.1')
    const version = fromDataRef.current.version || '1.1'
    navigate('/plugin?version=' + version, {
      replace: true
    })
  }

  // 原始 handleSave 函数
  const originalHandleSave = (type: string) => {
    if (type === 'save' && !hasFuncPermission([Func.tools.add])) {
      return
    } else if (type !== 'save' && !hasFuncPermission([Func.tools.publish])) {
      return
    }
    console.log('保存数据:', formState, fromDataRef.current)

    console.log(formState.getFieldsValue())

    formState
      .validateFields()
      .then(async obj => {
        const fromData = fromDataRef.current
        // 参数合并
        const data = {
          ...fromData,
          api_key: obj.apiKey || fromData.api_key,
          auth_method: obj.authMethod === 'apikey' ? 1 : 0,
          auth_type: obj.authType,
          name: obj.toolName,
          openapi_schema: obj.schemaContent,
          category_code: obj.category_code,
          description: obj.description,
          logo: obj.logo ? obj.logo : defaultIcon.current
        }
        let methodApi = delShow ? updateTool : createTool
        if (type && type == 'save') {
          methodApi = saveTool
        }

        // 创建 不新增 tool_id
        if (!delShow) {
          delete data.tool_id
        } else {
          // 编辑不能修改原有 tool_id
          data.tool_id = tool.tool_id
          data.version = tool.version
        }
        if (methodApi == createTool) {
          data.is_published = true
        }
        /* 编辑并且发布 */
        if (type === 'publish' && delShow) {
          try {
            const [flow_used_res]: any[] = await Promise.all([
              toolUsedCountByFlowApi(cur_tool_id.current || fromDataRef.current.tool_id)
            ])
            const flow_used_count = flow_used_res?.count || 0
            if (flow_used_count > 0) {
              confirm({
                title: t('prompt'),
                icon: <ExclamationCircleFilled style={{ color: 'red' }} />,
                content: `${`插件当前被${flow_used_count}个工作流引用，更新版本后，将导致所有引用的工作流无法使用，需重新调试，操作无法撒回，确认保存发布插件？`} `,
                okText: '确认',
                okType: 'danger',
                cancelText: t('cancel'),
                autoFocusButton: null,
                centered: true,
                destroyOnClose: true,
                onOk() {
                  publishTool(data, methodApi, type)
                }
              })
            } else {
              publishTool(data, methodApi, type)
            }
          } catch (error) {
            console.error('Failed to get delete count', error)
          }
          return
        }
        publishTool(data, methodApi, type)
      })
      .catch(err => {
        console.log('err', err)
      })
  }
  const publishTool = (data, methodApi, type) => {
    methodApi(data)
      .then(res => {
        if (methodApi == createTool) {
          pluginBuriedEvent({
            page: '创建自定义插件页面',
            event_name: '【完成发布】按钮',
            data_id: res?.id || null,
            detail: JSON.stringify({ 类型: data.category_code, 结果: !res ? '失败' : '成功' })
          })
        } else if (methodApi == updateTool) {
          pluginBuriedEvent({
            page: '编辑自定义插件页面',
            event_name: '【完成发布】按钮',
            data_id: fromDataRef.current.id,
            detail: JSON.stringify({ 类型: data.category_code, 结果: !res ? '失败' : '成功' })
          })
        }
        if (!res) return
        if (type && type == 'save') {
          showMessage({
            content: t('保存成功'),
            type: 'success'
          })
        } else {
          showMessage({
            content: t('发布成功'),
            type: 'success'
          })
        }

        setEditShow(false)
        refreshPage()
      })
      .catch(err => {
        console.log(err)
        if (methodApi == createTool) {
          pluginBuriedEvent({
            page: '创建自定义插件页面',
            event_name: '【完成发布】按钮',
            detail: JSON.stringify({ 类型: data.category_code, 结果: '失败' })
          })
        } else if (methodApi == updateTool) {
          pluginBuriedEvent({
            page: '编辑自定义插件页面',
            event_name: '【完成编辑】按钮',
            data_id: fromDataRef.current.id,
            detail: JSON.stringify({ 类型: data.category_code, 结果: '失败' })
          })
        }
      })
  }

  //  debounce 包装 handleSave 函数
  const handleSave = debounce(originalHandleSave, 1000)

  // 确保在组件卸载时取消任何挂起的调用
  useEffect(() => {
    return () => {
      handleSave.cancel() // 取消所有挂起的防抖调用
    }
  }, [])

  // 删除插件
  const handleDelete = async e => {
    if (!hasFuncPermission([Func.tools.del])) {
      return
    }

    try {
      const [ast_used_res, flow_used_res]: any[] = await Promise.all([
        deleteToolCount({
          tool_id: cur_tool_id.current || fromDataRef.current.tool_id
        }),
        toolUsedCountByFlowApi(cur_tool_id.current || fromDataRef.current.tool_id)
      ])

      const ast_used_count = ast_used_res?.count || 0
      const flow_used_count = flow_used_res?.count || 0
      confirm({
        title: t('prompt'),
        icon: <ExclamationCircleFilled style={{ color: 'red' }} />,
        content: `${
          ast_used_count || flow_used_count
            ? `插件当前被${ast_used_count}个智能体、${flow_used_count}个工作流引用。删除后，将导致所有引用的智能体或工作流无法使用，操作无法撤回，确认删除该插件?`
            : t('skills.deleteSure')
        } `,
        okText: t('delete'),
        okType: 'danger',
        cancelText: t('cancel'),
        autoFocusButton: null,
        centered: true,
        destroyOnClose: true,
        onOk() {
          pluginBuriedEvent({
            page: '编辑自定义插件页面',
            event_name: '【删除】按钮',
            data_id: fromDataRef.current.id
          })
          // api
          captureAndAlertRequestErrorHoc(deleteTool(fromDataRef.current.tool_id))
            .then(res => {
              pluginBuriedEvent({
                page: '编辑自定义插件页面',
                event_name: '确定【删除】按钮',
                data_id: fromDataRef.current.id,
                detail: JSON.stringify({ 结果: res === false ? '失败' : '成功' })
              })
              if (res === false) return
              refreshPage()
              setEditShow(false)
            })
            .catch(err => {
              console.log(err)
              pluginBuriedEvent({
                page: '编辑自定义插件页面',
                event_name: '确定【删除】按钮',
                data_id: fromDataRef.current.id,
                detail: JSON.stringify({ 结果: '失败' })
              })
            })
        }
      })
    } catch (error) {
      console.error('Failed to get delete count', error)
    }
  }

  // test
  const testDialogRef = useRef(null)
  const handleTest = obj => {
    testDialogRef.current.open(obj)
  }
  const { t } = useTranslation()

  const handleBack = () => {
    /* 
        listSee   = 列表点击查看 = 返回并跳到自定义
        oldseeNum = 点击切换版本or查看 是否会退数据
    */
    if (id !== '0') {
      pluginBuriedEvent({
        page: '编辑自定义插件页面',
        event_name: '【返回】按钮',
        data_id: fromDataRef.current.id
      })
    } else {
      pluginBuriedEvent({
        page: '创建自定义插件页面',
        event_name: '【返回】按钮'
      })
    }
    if (tool?.hidType === 'listSee') {
      localStorage.setItem('plugin_tool_id', fromDataRef.current.version || '1.1')
      navigate('/plugin?version=' + fromDataRef.current.version, {
        replace: true
      })
    } else if (oldseeNum === 1) {
      const matchedItem = versionList.find(item => item.version === oldseeInfoNum)
      if (matchedItem) {
        handelVersionChange(matchedItem)
      } else {
        console.error('No matching item found')
      }
      SetoldseeNum(0)
      SetSeeType(true)
    } else {
      navigate('/plugin', {
        replace: true
      })
    }
  }

  const handleSelectPic = pic => {
    formState.setFieldsValue({ logo: pic })
  }

  const [authType, setAuthType] = useState(formState.getFieldValue('authMethod'))
  const handleValueChange = () => {
    // console.log(formState.getFieldsValue(), '表单值变化')
  }

  /* 版本查看区分 */
  const [seeType, SetSeeType] = useState(true)
  const [oldseeNum, SetoldseeNum] = useState(0)
  const [oldseeInfoNum, SetoldseeInfoNum] = useState('')
  // page信息
  const pageinfo = {
    size: 10,
    pageNum: 1,
    total: 500,
    version: ''
  }
  const [RecordPage, SetRecordPage] = useState(pageinfo)
  const [RecordsHid, SetRecordsHid] = useState(false)
  // 打开
  const onRecords = () => {
    if (!hasFuncPermission([Func.tools.version])) {
      return
    }
    SetRecordPage({
      ...RecordPage,
      pageNum: 1,
      version: fromDataRef?.current?.version ? fromDataRef?.current?.version : ''
    })
    setTimeout(() => {
      console.log('onRecords', RecordPage)
    }, 1000)
    SetRecordsHid(true)
  }
  const recordPage = e => {
    console.log(e, '分页信息')
    // SetRecordPage({ ...RecordPage, pageNum: 1 })
    /* updata list */
  }
  // 查看版本
  const handleVersion = e => {
    handelVersionChange(e)
    SetSeeType(false)
  }
  // 取消
  const closeFun = () => {
    SetRecordsHid(false)
  }

  const updateResultStatus = () => {
    console.log('>>更新测试结果', fromDataRef.current)
    if (fromDataRef.current?.children) {
      setTableData(fromDataRef.current?.children)
    }
  }
  const getTestResultSpan = status => {
    switch (status) {
      case 1:
        return <span className="result_success">成功</span>
      case 2:
        return <span className="result_error">失败</span>
      default:
        return <span className="result_none">未测试</span>
    }
  }

  return (
    <div className="edit-tool-page-container relative h-full w-full px-[32px] py-[32px]">
      <Form
        className="login-form rounded-[6px] bg-[#ffffff]"
        layout="vertical"
        form={formState}
        initialValues={initFormData}
        onValuesChange={() => handleValueChange()}
      >
        <div className="w-6/12">
          <div className="px-[32px] pb-[24px] pt-[32px] font-semibold">
            {/* @ts-expect-error : Argument of type 'className' is effective */}
            <BackIcon className="mr-[10px] inline-block cursor-pointer" onClick={() => handleBack()}></BackIcon>
            {!seeType ? t('tools.version') : delShow ? t('edit') : t('create')}
            {seeType ? t('tools.createCustomTool') : fromDataRef.current.version}
          </div>
          <div className="">
            {/* name */}
            <div className="px-[32px]">
              <Form.Item
                name="toolName"
                label={t('tools.plugin') + t('tools.name')}
                required
                rules={[
                  { required: true, message: t('lib.nullLimit') },
                  { max: 30, message: t('lib.limit30Len') }
                ]}
              >
                <AntInput
                  disabled={!seeType}
                  autoComplete="off"
                  className=" w-[300px]"
                  placeholder={t('tools.enterToolName')}
                />
              </Form.Item>
            </div>
          </div>
        </div>

        {/* 类型 */}

        {/* <div className="px-[32px]">
          <Form.Item
            name="category_code"
            label={t('tools.type')}
            rules={[{ required: true, message: t('lib.nullLimit') }]}
          >
            <Radio.Group disabled={!seeType}>
              {typeList?.length &&
                typeList.map(({ id, label, value }) => (
                  <Radio key={id} value={value}>
                    {label}
                  </Radio>
                ))}
            </Radio.Group>
          </Form.Item>
        </div> */}

        <div className="w-6/12">
          {/* 插件描述 */}
          <div className="px-[32px]">
            <Form.Item
              name="description"
              label={t('tools.description')}
              rules={[
                { required: true, message: t('lib.nullLimit') },
                { max: 255, message: t('lib.limit255Len') }
              ]}
            >
              <TextArea
                disabled={!seeType}
                placeholder={'请描述这个插件的功能和用途，以便大模型更好地理解并进行调用'}
                autoSize={{ minRows: 3 }}
              />
            </Form.Item>
          </div>

          {/* 插件版本 */}
          {delShow ? (
            <>
              <div className="flex items-center px-[32px] text-sm">
                <Form.Item name="version" label={t('tools.version')}>
                  <AntInput className="mr-[10px] mt-2 w-[300px]" disabled />
                </Form.Item>
                {seeType ? (
                  <span className="cursonCase mt-[10px]" onClick={onRecords}>
                    查看
                    <span className="text-[#1677ff]">其他版本</span>
                  </span>
                ) : null}
              </div>
            </>
          ) : null}

          {/* schema */}
          <div className="flex items-center justify-between px-[32px]">
            <label htmlFor="open" className="plugin-family common-required-item">
              OpenAPI 配置信息
            </label>
            <div className="flex gap-2">
              <CustomSelect
                disabled={!seeType}
                defaultValue={t('tools.examples')}
                style={{ width: 120 }}
                onChange={k => handleSelectTemplate(k)}
                options={[
                  { value: 'json', label: t('tools.weatherJson') },
                  { value: 'yaml', label: t('tools.weatherYaml') }
                ]}
              ></CustomSelect>
            </div>
          </div>
          <div className="flex items-center justify-start px-[32px] py-[8px]">
            <div className="schema-prompt-el schema-prompt-el-black">
              <span>需配置的属性名称</span>
            </div>
            <div className="schema-prompt-el schema-prompt-el-red">
              <span>需填写的属性值</span>
            </div>
            <div className="schema-prompt-el schema-prompt-el-gray">
              <span>注释</span>
            </div>
          </div>
          <div className="mb-4 px-[32px]">
            <Form.Item name="schemaContent" rules={[{ required: true, message: t('lib.nullLimit') }]}>
              <AceEditor
                readOnly={!seeType}
                name="toolConfigEditor"
                mode={aceMode}
                // @ts-expect-error no issue，Ignore this prompt
                value={formState.schemaContent || ''}
                highlightActiveLine={true}
                showPrintMargin={false}
                fontSize={14}
                showGutter={false}
                wrapEnabled={true}
                onBlur={() => handleSelectTemplate()}
                onChange={value => handleAceDataChange(value)}
                className={`plugin-tool-config-editor plugin-tool-config-editor-${aceMode}`}
              />
            </Form.Item>
          </div>

          <label htmlFor="open" className="plugin-family px-[32px] ">
            {t('tools.authenticationType')}
          </label>
          <div className="px-6">
            <div className="mb-4 px-6">
              <Form.Item name="authMethod">
                <Radio.Group disabled={!seeType}>
                  <Radio key="1" id="1" value="none">
                    {t('tools.none')}
                  </Radio>
                  <Radio key="2" id="2" value="apikey">
                    {t('tools.apiKey')}
                  </Radio>
                </Radio.Group>
              </Form.Item>
            </div>

            {authMethodValue === 'apikey' && (
              <>
                <div className="mb-4 px-6">
                  <Form.Item
                    name="apiKey"
                    label={'API Key'}
                    required
                    rules={[{ required: true, message: t('lib.nullLimit') }]}
                  >
                    <AntInput autoComplete="off" className="" />
                  </Form.Item>
                </div>

                <div className="mb-4 px-6">
                  <Form.Item name="authType" label={'Auth Type'}>
                    <Radio.Group>
                      <Radio key="1" id="1" value="basic">
                        Basic
                      </Radio>
                      <Radio key="2" id="2" value="bearer">
                        Bearer
                      </Radio>
                    </Radio.Group>
                  </Form.Item>
                </div>
              </>
            )}

            {/* {formState.authMethod === "custom" && (
                            <div className="px-6 mb-4">
                                <label htmlFor="customHeader">Custom Header Name</label>
                                <Input
                                    id="customHeader"
                                    name="customHeader"
                                    className="mt-2"
                                    value={formState.customHeader}
                                    onChange={handleInputChange}
                                />
                            </div>
                        )} */}
          </div>
        </div>
        <label htmlFor="open" className="plugin-family px-[32px] ">
          已配置OpenAPI工具
        </label>

        <div className="mb-4 w-full px-[32px]">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead className="w-[100px]">{t('tools.name')}</TableHead>
                <TableHead>{t('tools.description')}</TableHead>
                <TableHead>{t('tools.method')}</TableHead>
                <TableHead>更新时间</TableHead>
                {/* <TableHead>{t('tools.path')}</TableHead> */}
                <TableHead>状态</TableHead>
                <TableHead>{t('operations')}</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {tableData.length ? (
                tableData.map((item, index) => (
                  <TableRow key={index}>
                    <TableCell>{item.name}</TableCell>
                    <TableCell>{item.desc}</TableCell>
                    <TableCell>{item.extra?.method || '--'}</TableCell>
                    {/* <TableCell>{item.extra?.path}</TableCell> */}
                    <TableCell>{item.update_time ? item.update_time.replace('T', ' ') : '--'}</TableCell>
                    <TableCell>
                      <div className="test-result-status">{getTestResultSpan(item.pass_test)}</div>
                    </TableCell>
                    <TableCell>
                      <span
                        style={{ fontSize: '14px', fontWeight: '400' }}
                        onClick={() => {
                          if (!seeType) {
                            return
                          }
                          testDialogRef.current.open(item, fromDataRef.current, index)
                        }}
                        className={!seeType ? 'cursoNot px-0 text-[#006BFD]' : 'cursonCase px-0 text-[#006BFD]'}
                      >
                        {t('test.test')}
                      </span>
                    </TableCell>
                  </TableRow>
                ))
              ) : (
                <TableRow>
                  <TableCell colSpan={6}>{t('tools.none')}</TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </div>

        {/* <label htmlFor="open" className="px-6">{t('tools.authenticationType')}</label>
                <div className="px-6">
                    <div className="px-6 mb-4" >
                        <label htmlFor="open" className="bisheng-label">{t('tools.authType')}</label>
                        <RadioGroup
                            id="authMethod"
                            name="authMethod"
                            defaultValue="none"
                            className="flex mt-2 gap-4"
                            onValueChange={(value) => formState.setFieldsValue(prevState => ({ ...prevState, authMethod: value }))}
                        >
                            <div className="flex items-center space-x-2">
                                <RadioGroupItem value="none" id="r1" />
                                <Label htmlFor="r1">{t('tools.none')}</Label>
                            </div>
                            <div className="flex items-center space-x-2">
                                <RadioGroupItem value="apikey" id="r2" />
                                <Label htmlFor="r2">{t('tools.apiKey')}</Label>
                            </div>
                        </RadioGroup>
                    </div>
                    {formState.authMethod === "apikey" && (
                        <div className="px-6 mb-4">
                            <label htmlFor="apiKey">{t('tools.apiKey')}</label>
                            <Input
                                id="apiKey"
                                name="apiKey"
                                className="mt-2"
                                value={formState.apiKey}
                                onChange={handleInputChange}
                            />
                        </div>
                    )}
                </div> */}

        <div className="w-6/12">
          {seeType ? (
            <div className="uploadCase_post px-[32px]">
              <IconUpload
                // @ts-expect-error : Argument of type 'fileList' is effective
                defaultFileList={formState.fileList}
                form={formState}
                validateNames={['toolName', 'description']}
                logo={formState.getFieldValue('logo')}
                onSelect={pic => handleSelectPic(pic)}
                setDefault={setDefaultIcon}
              ></IconUpload>
              <Form.Item name="logo"></Form.Item>
            </div>
          ) : null}
          {seeType ? (
            <div className=" bottom-0 right-0 w-full bg-[#fff] px-[32px] py-4">
              {delShow && (
                <AntdButton
                  disabled={!seeType}
                  danger
                  type="primary"
                  shape="round"
                  className="mr-[10px]"
                  onClick={handleDelete}
                >
                  {t('tools.delete')}
                </AntdButton>
              )}

              <ThemeBtn
                size="sm"
                className="mr-[10px]"
                onClick={e => {
                  handleSave('save')
                }}
              >
                {t('tools.save')}
              </ThemeBtn>

              <ThemeBtn
                size="sm"
                className="mr-[10px]"
                onClick={() => {
                  handleSave('publish')
                }}
              >
                {/* {delShow ? t('tools.finishEdit') : t('tools.finishCreate')} */}
                完成发布
              </ThemeBtn>

              <AntdButton
                type="default"
                className="closeBtnStyles"
                shape="round"
                onClick={() => {
                  if (id !== '0') {
                    pluginBuriedEvent({
                      page: '编辑自定义插件页面',
                      event_name: '【取消】按钮',
                      data_id: fromDataRef.current.id
                    })
                  } else {
                    pluginBuriedEvent({
                      page: '创建自定义插件页面',
                      event_name: '【取消】按钮'
                    })
                  }
                  /* 判断新增的取消按钮 */
                  if (!delShow) {
                    navigate('/plugin')
                    return
                  }
                  refreshPage()
                }}
              >
                {t('tools.cancel')}
              </AntdButton>
            </div>
          ) : null}
          {!seeType ? <div className=" bottom-0 right-0 w-full bg-[#fff] px-[32px] py-4"></div> : null}
        </div>
      </Form>

      <TestDialog ref={testDialogRef} updateStatus={updateResultStatus} />
      {/* 版本记录 */}
      {RecordsHid ? (
        <Edition
          recordList={versionList}
          RecordPage={RecordPage}
          recordPage={e => {
            recordPage(e)
          }}
          RadioChang={e => {
            handelVersionChange(e)
            SetSeeType(true)
          }}
          radioType={false}
          // closable={false}
          // title={''}
          closeFun={closeFun}
          handleVersion={e => {
            handleVersion(e)
          }}
        ></Edition>
      ) : null}
    </div>
  )
})

const TestDialog = forwardRef(({ updateStatus = () => {} }: any, ref) => {
  const { t } = useTranslation()
  const [testShow, setTestShow] = useState(false)
  const [apiData, setApiData] = useState<any>({})
  const toolRef = useRef<any>({})
  const formRef = useRef<any>({})
  const formRuleRef = useRef<any>({})
  const [tableIndex, settableIndex] = useState(null)

  console.log(ref, 'refrefrefref')

  useImperativeHandle(ref, () => ({
    open: (item, tool, index) => {
      toolRef.current = tool
      settableIndex(index)
      setResult('')
      setApiData(item)
      setTestShow(true)
      // fill form
      item.api_params.forEach(param => {
        formRef.current[param.name] = ''
        formRuleRef.current[param.name] = param.required
      })
      console.log(tool, 'item=item=item')
    }
  }))
  // 重置
  useEffect(() => {
    if (!testShow) {
      formRef.current = {}
      formRuleRef.current = {}
    }
  }, [testShow])

  const [loading, setLoading] = useState(false)
  const [result, setResult] = useState(null)
  const handleTest = async () => {
    // 校验
    const errors = []
    Object.keys(formRef.current).forEach(key => {
      if (formRuleRef.current[key] && formRef.current[key] === '') {
        errors.push(key + '为必填项')
      }
    })
    if (errors.length > 0) {
      return showMessage({
        content: errors,
        type: 'warning'
      })
    }

    setLoading(true)
    const { server_host, children, auth_method, auth_type, api_key } = toolRef.current

    testToolApi({
      server_host,
      extra: children.find(el => el.name === apiData.name).extra,
      auth_method,
      auth_type,
      api_key,
      request_params: formRef.current
    })
      .then(res => {
        let pass_test = 2
        if (res?.data?.code === 200) {
          pass_test = 1
        }
        const list = toolRef.current.children || []
        toolRef.current.children = list.map((item, index) => {
          if (index === tableIndex) {
            return {
              ...item,
              pass_test
            }
          } else {
            return item
          }
        })
        updateStatus()
        setResult(res?.data)
      })
      .catch(error_info => {
        showError('提示', error_info)
      })
      .finally(() => {
        setLoading(false)
      })
  }

  return (
    <Dialog open={testShow} onOpenChange={setTestShow}>
      <DialogContent className="sm:max-w-[625px]">
        <DialogHeader>
          <DialogTitle>{apiData.name}</DialogTitle>
        </DialogHeader>
        {testShow && (
          <div className="flex flex-col">
            <div className="max-h-[600px] overflow-y-auto scrollbar-hide">
              {/* <label htmlFor="name" className="bisheng-label">
                {t('test.parametersAndValues')}
              </label> */}
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead className="w-[100px]">
                      <span className="inter_size">{t('test.parameter')}</span>
                    </TableHead>
                    <TableHead>
                      <span className="inter_size">{t('test.value')}</span>
                    </TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {apiData.api_params.map(param => (
                    <TableRow key={param.name + Math.round(Math.random() * 100000000)}>
                      <TableCell>
                        <span className="inter_size">{param.name}</span>
                        {param.required && <span className="text-red-500">*</span>}
                      </TableCell>
                      <TableCell>
                        <AntInput
                          defaultValue={formRef.current[param.name]}
                          style={{ height: '38px' }}
                          onChange={e => {
                            formRef.current[param.name] = e.target.value
                          }}
                          disabled={loading}
                        ></AntInput>
                      </TableCell>
                    </TableRow>
                  ))}
                  {apiData.api_params.length === 0 && (
                    <TableRow>
                      <TableCell colSpan={2}>None</TableCell>
                    </TableRow>
                  )}
                </TableBody>
              </Table>
            </div>
            <Button type="primary" className="inter_btn flexRow" onClick={handleTest} loading={loading}>
              {loading ? '测试中' : '测试'}
            </Button>
            {result ? (
              <div className="">
                <label htmlFor="desc" className="bisheng-label">
                  <div className="flexRowStart">
                    <span className="inter_size">{t('test.result')}：</span>
                    {result?.code == 200 ? (
                      <>
                        <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                          <circle cx="8" cy="8" r="7" fill="#38D0AF" />
                          <path
                            d="M10.9668 6.81055L7.81031 9.96703L5.99952 8.15624"
                            stroke="white"
                            strokeWidth="1.5"
                            strokeLinecap="round"
                            strokeLinejoin="round"
                          />
                        </svg>
                        <span style={{ marginLeft: '4px' }}>通过</span>
                      </>
                    ) : (
                      <>
                        <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                          <circle cx="8" cy="8" r="7" fill="#FA514B" />
                          <path
                            d="M5.87891 5.87891L10.1215 10.1215"
                            stroke="white"
                            strokeWidth="1.5"
                            strokeLinecap="round"
                            strokeLinejoin="round"
                          />
                          <path
                            d="M5.87891 10.1211L10.1215 5.87845"
                            stroke="white"
                            strokeWidth="1.5"
                            strokeLinecap="round"
                            strokeLinejoin="round"
                          />
                        </svg>
                        <span style={{ marginLeft: '4px' }}>失败</span>
                      </>
                    )}
                  </div>
                </label>
                <TextArea
                  id="desc"
                  name="desc"
                  value={JSON.stringify(result)}
                  placeholder={t('test.outResultPlaceholder')}
                  readOnly
                  className="mt-2"
                />
              </div>
            ) : null}
          </div>
        )}
      </DialogContent>
    </Dialog>
  )
})

export default EditTool

const useApiTableData = () => {
  const [tableData, setTableData] = useState([])

  const setData = objs => {
    const newObjs = objs.map(obj => {
      return {
        ...obj,
        extra: JSON.parse(obj.extra || '{}')
      }
    })

    setTableData(newObjs)
  }

  return [tableData, setData] as const
}

// 示例
const Example = {
  json: `{  # 开始JSON文档
  "openapi": "3.0.2",  # OpenAPI规范版本
  "info": {  # 描述API的基本信息
    "title": "天气查询 API",  # API标题
    "description": "查询各地天气信息",  # API描述
    "version": "1.0.0"  # API版本
  },
  "servers": [  # API服务器配置
    {  # 服务器URL配置
      "url": "https://restapi.amap.com/v3/weather"  # API的URL
    }
  ],
  "paths": {  # API路径定义
    "/weatherInfo": {  # 路径操作
      "get": {  # GET方法定义
        "summary": "获取天气信息",  # 方法的简要描述
        "operationId": "getWeatherInfo",  # 操作ID
        "parameters": [  # 请求参数列表
          {  # API密钥参数
            "in": "query",  # 参数的位置
            "name": "key",  # 参数名
            "required": true,  # 是否必须
            "schema": {  # 参数的模式
              "type": "string",  # 参数类型
              "default": "ac627cc80b149eadc10210c06a3055ec"  # 默认值
            },
            "description": "api请求参数key默认是ac627cc80b149eadc10210c06a3055ec"  # 参数描述
          },
          {  # 查询城市的参数
            "in": "query",  # 参数的位置
            "name": "city",  # 参数名
            "required": true,  # 是否必须
            "schema": {  # 参数的模式
              "type": "string"  # 参数类型
            },
            "description": "从用户问题中提取需要查询天气的地点，规则：如果句子中有具体的县/区名称，则提取县/区名称"  # 参数描述
          },
          {  # 扩展信息参数
            "in": "query",  # 参数的位置
            "name": "extensions",  # 参数名
            "required": false,  # 是否必须
            "schema": {  # 参数的模式
              "type": "string",  # 参数类型
              "enum": [  # 允许的枚举值
                "base",
                "all"
              ],
              "default": "base"  # 默认值
            },
            "description": "气象类型 (base: 实况天气, all: 预报天气)"  # 参数描述
          },
          {  # 输出格式参数
            "in": "query",  # 参数的位置
            "name": "output",  # 参数名
            "required": false,  # 是否必须
            "schema": {  # 参数的模式
              "type": "string",  # 参数类型
              "enum": [  # 允许的枚举值
                "JSON",
                "XML"
              ],
              "default": "JSON"  # 默认值
            },
            "description": "返回格式"  # 参数描述
          }
        ],
        "responses": {  # 响应对象
          "200": {  # HTTP状态码
            "description": "成功响应",  # 响应描述
            "content": {  # 响应内容
              "application/json": {  # 响应媒体类型
                "schema": {  # 响应数据模式
                  "type": "object",  # 响应对象类型
                  "properties": {  # 响应对象属性
                    "status": {  # 状态码
                      "type": "integer",  # 类型
                      "description": "返回状态 (1: 成功, 0: 失败)"  # 描述
                    },
                    "count": {  # 结果数量
                      "type": "integer",  # 类型
                      "description": "返回结果数量"  # 描述
                    },
                    "info": {  # 状态信息
                      "type": "string",  # 类型
                      "description": "状态信息"  # 描述
                    },
                    "infocode": {  # 状态码说明
                      "type": "string",  # 类型
                      "description": "状态码 (10000: 正确)"  # 描述
                    },
                    "lives": {  # 实况天气数据
                      "type": "array",  # 类型
                      "items": {  # 数组中的对象
                        "type": "object",  # 对象类型
                        "description": "实况天气数据"  # 描述
                      }
                    },
                    "forecast": {  # 天气预报数据
                      "type": "array",  # 类型
                      "items": {  # 数组中的对象
                        "type": "object",  # 对象类型
                        "description": "天气预报数据"  # 描述
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}  # 结束JSON文档`,
  yaml: `# 开始 YAML 文档
openapi: 3.0.2  # OpenAPI 规范版本

# 描述 API 的基本信息
info:
  title: 天气查询 API  # API 标题
  description: 查询各地天气信息  # API 描述
  version: 1.0.0  # API 版本

# API 服务器配置
servers:
  - url: https://restapi.amap.com/v3/weather  # API 的 URL

# API 路径定义
paths:
  /weatherInfo:  # 路径操作
    get:  # GET 方法定义
      summary: 获取天气信息  # 方法的简要描述
      operationId: getWeatherInfo  # 操作 ID
      parameters:  # 请求参数列表
        - in: query  # 参数的位置
          name: key  # 参数名
          required: true  # 是否必须
          schema:  # 参数的模式
            type: string  # 参数类型
            default: ac627cc80b149eadc10210c06a3055ec  # 默认值
          description: api请求参数key默认是ac627cc80b149eadc10210c06a3055ec  # 参数描述
        - in: query  # 参数的位置
          name: city  # 参数名
          required: true  # 是否必须
          schema:  # 参数的模式
            type: string  # 参数类型
          description: 从用户问题中提取需要查询天气的地点，规则：如果句子中有具体的县/区名称，则提取县/区名称  # 参数描述
        - in: query  # 参数的位置
          name: extensions  # 参数名
          required: false  # 是否必须
          schema:  # 参数的模式
            type: string  # 参数类型
            enum:  # 允许的枚举值
              - base
              - all
            default: base  # 默认值
          description: 气象类型 (base：实况天气, all： 预报天气)  # 参数描述
        - in: query  # 参数的位置
          name: output  # 参数名
          required: false  # 是否必须
          schema:  # 参数的模式
            type: string  # 参数类型
            enum:  # 允许的枚举值
              - JSON
              - XML
            default: JSON  # 默认值
          description: 返回格式  # 参数描述
      responses:  # 响应对象
        '200':  # HTTP 状态码
          description: 成功响应  # 响应描述
          content:  # 响应内容
            application/json:  # 响应媒体类型
              schema:  # 响应数据模式
                type: object  # 响应对象类型
                properties:  # 响应对象属性
                  status:  # 状态码
                    type: integer  # 类型
                    description: 返回状态 (1：成功, 0： 失败)  # 描述
                  count:  # 结果数量
                    type: integer  # 类型
                    description: 返回结果数量  # 描述
                  info:  # 状态信息
                    type: string  # 类型
                    description: 状态信息  # 描述
                  infocode:  # 状态码说明
                    type: string  # 类型
                    description: 状态码 (10000：正确)  # 描述
                  lives:  # 实况天气数据
                    type: array  # 类型
                    items:  # 数组中的对象
                      type: object  # 对象类型
                      description: 实况天气数据  # 描述
                  forecast:  # 天气预报数据
                    type: array  # 类型
                    items:  # 数组中的对象
                      type: object  # 对象类型
                      description: 天气预报数据  # 描述

# 结束 YAML 文档`
}
